package com.customds.impl;

/*
	Author: Leo
	Creation Date: 4-8-2012
	Creation Time: 12:49 AM
*/

import java.util.*;
import java.sql.*;

public class TableDataRetriever {
	// Data member declaration	
	ResultSetMetaData md;
	int maxColumnIndex; // Number of columns
	int columnIndex; // Index of a column
	// String columnType;
	String columnName;
	
	ArrayList<String> columnValues;
	ArrayList<String> resultantList;
	Map<String, ArrayList<String>> columnData;
	
	// Constructor
	public TableDataRetriever() {
		md = null;
		maxColumnIndex = -1;
		// columnIndex = -1;
		// columnType = "";
		columnName = "";
		
		columnValues = new ArrayList<String>();
		resultantList = new ArrayList<String>();
		columnData = new LinkedHashMap<String, ArrayList<String>>();
	} // End of constructor
	
	protected Map<String, ArrayList<String>> getColumnWithMetaData(ResultSet rs) throws SQLException {
		int i; // Counter Variable
		md = rs.getMetaData();
		maxColumnIndex = md.getColumnCount();
		
		// Legacy code
		/*
		for(i = 1; i <= maxColumnIndex; i++) {
			if(columnName.equalsIgnoreCase(md.getColumnName(i))) {
				columnIndex = i;
				break;
			}
		} // End of for-loop
		*/
		
		// Get column's SQL type
		// columnType = md.getColumnTypeName(columnIndex);
		
		for(i = 1; i <= maxColumnIndex; i++) {
			// Reset ResultSet cursor position and ArrayList before use
			rs.absolute(1);
			columnValues = new ArrayList<String>();
			
			// Get column header
			columnName = md.getColumnName(i);
			
			// Get column data in an ArrayList
			do {
				columnValues.add(rs.getString(i));
			} while(rs.next());
			
			// Put everything into a LinkedHashMap
			columnData.put(columnName, columnValues);
		} // End of for-loop
				
		// Legacy code
		/*
		for(Map.Entry<String, ArrayList<String>> entry : columnData.entrySet()) {
			resultantList = entry.getValue();
			
			// Display column header and column values
			System.out.println("Column name: " + entry.getKey());
			
			for(String cData : resultantList) {
				System.out.println(cData);
			} // End of inner for-loop
			
			System.out.print("\n");
		} // End of outer for-loop
		*/
		
		return columnData;
	} // End of method
	
	public int getTableSize() {		
		return columnValues.size();
	} // End of method
	
} // End of class